package com.opennews.openplatform.familyexpenseapi.controller

import com.opennews.openplatform.familyexpenseapi.dto.file.AvatarByBase64Dto
import com.opennews.openplatform.familyexpenseapi.service.FileService
import com.opennews.openplatform.myspringbootcore.dto.ApiResponse
import com.opennews.openplatform.myspringbootcore.util.getSuccessResponse
import com.opennews.openplatform.myspringbootmvccore.security.RequestIdentityExtractor
import jakarta.servlet.ServletOutputStream
import jakarta.servlet.http.HttpServletResponse
import jakarta.validation.Valid
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile

@RestController
@RequestMapping("/file")
class FileController(
    private val fileService: FileService,
    private val requestIdentityExtractor: RequestIdentityExtractor,
    private val response: HttpServletResponse,
) {
    @GetMapping("/download")
    @ResponseStatus(HttpStatus.OK)
    fun download() {
        val filename = "book.csv"

        // Sets the response headers.
        response.contentType = "application/csv"
        response.setHeader("Content-Disposition", "attachment; filename=$filename")

        // Writes content to response output stream.
        response.outputStream.use { outputStream: ServletOutputStream ->
            outputStream.write("This is testing".toByteArray())
            outputStream.flush()
        }
    }

    @PostMapping("/upload-own-avatar-by-base64")
    fun uploadOwnAvatarByBase64(@Valid @RequestBody data: AvatarByBase64Dto): ResponseEntity<ApiResponse<String>> {
        // Gets current user's id to update the avatar info.
        val userId = requestIdentityExtractor.getClaims().id.asString()

        // Uploads the avatar file and updates the user avatar info.
        val avatarUrl = fileService.uploadAvatarByBase64(userId, data.filename, data.base64Content)

        // Sends the avatar url back to client.
        return getSuccessResponse(avatarUrl)
    }

    @PostMapping("/upload")
    fun uploadFile(@RequestParam("files") files: List<MultipartFile>): ResponseEntity<String> {
        for (file in files) {
            println("Uploading file ${file.originalFilename}")
        }

        //            // Ensure directory exists
        //            val uploadDir = File("D:\\Temp\\family-expense-resources");
        //
        //            if (!uploadDir.exists()) {
        //                uploadDir.mkdirs();
        //            }
        //
        //            // Save file to the server
        //            val serverFile = new File("UPLOAD_DIR" + file.getOriginalFilename());
        return ResponseEntity.ok("File uploaded successfully: ")
    }
}